﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Forms;
using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Commands;
using MaxStoreShop.Core.Contracts;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.CoreModule.Settings
{
    class SettingsPresenter : PresenterBase<SettingsView, SettingsViewModel>
    {
        [Dependency]
        public ISettings Settings { get; set; }

        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.BrowseWorkFolderCommand = new RelayCommand(BrowseWorkFolder);
            ViewModel.BrowseUpdateFolderCommand = new RelayCommand(BrowseUpdateFolder);
            ViewModel.CheckConnectionCommand = new RelayCommand(CheckConnection);
        }

        protected override void OnViewSet()
        {
            base.OnViewSet();
            System.Windows.Application.Current.Exit += CurrentOnExit;
        }

        void CurrentOnExit(object sender, ExitEventArgs e)
        {
            SaveSettings();
        }

        void BrowseUpdateFolder()
        {
            var updateFolder = GetFolderPath(ViewModel.UpdateFolder);
            if (string.IsNullOrWhiteSpace(updateFolder))
                return;

            ViewModel.UpdateFolder = updateFolder;
        }

        void BrowseWorkFolder()
        {
            var workFolder = GetFolderPath(ViewModel.WorkFolder);
            if (string.IsNullOrWhiteSpace(workFolder))
                return;

            ViewModel.WorkFolder = workFolder;
        }

        static string GetFolderPath(string selectedPath)
        {
            var folderBrowser = new FolderBrowserDialog
            {
                RootFolder = Environment.SpecialFolder.MyComputer,
                SelectedPath = selectedPath,
                ShowNewFolderButton = true
            };

            return folderBrowser.ShowDialog() != DialogResult.OK ? string.Empty : folderBrowser.SelectedPath;
        }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            ViewModel.WorkFolder = Settings.WorkFolder;
            var builder = new SqlConnectionStringBuilder(Settings.ConnectionString);
            ViewModel.ServerName = builder.DataSource;
            ViewModel.DataBaseName = builder.InitialCatalog;
            ViewModel.UpdateFolder = Settings.UpdateFolder;
            if (!builder.IntegratedSecurity)
            {
                View.UserSecurityRadioButton.IsChecked = true;
                ViewModel.UserId = builder.UserID;
                ViewModel.Password = builder.Password;
            }
        }

        void SaveSettings()
        {
            var builder = new SqlConnectionStringBuilder
            {
                DataSource = ViewModel.ServerName,
                InitialCatalog = ViewModel.DataBaseName
            };
            if (View.NtSecurityRadioButton.IsChecked == true)
            {
                builder.IntegratedSecurity = true;
                builder.MultipleActiveResultSets = true;
            }
            else
            {
                builder.UserID = ViewModel.UserId;
                builder.Password = ViewModel.Password;
            }

            Settings.ConnectionString = builder.ToString();


            Settings.WorkFolder = ViewModel.WorkFolder;
            Settings.UpdateFolder = ViewModel.UpdateFolder;
        }

        void CheckConnection()
        {
            try
            {
                var builder = new SqlConnectionStringBuilder
                {
                    DataSource = ViewModel.ServerName,
                    InitialCatalog = ViewModel.DataBaseName,
                    ConnectTimeout = 5
                };
                if (View.NtSecurityRadioButton.IsChecked == true)
                {
                    builder.IntegratedSecurity = true;
                    builder.MultipleActiveResultSets = true;
                }
                else
                {
                    builder.UserID = ViewModel.UserId;
                    builder.Password = ViewModel.Password;
                }

                using (var connection = new SqlConnection(builder.ToString()))
                {
                    connection.Open();

                    if (connection.State == ConnectionState.Open)
                    {
                        UserMessage.InfoMessageAsync("Тест подключения успешно пройден", "Тест подключения");
                    }
                    else
                    {
                        UserMessage.InfoMessageAsync("Не удалось установить подключение к удаленному узлу",
                            "Тест подключения");
                    }
                    connection.Close();
                }
            }
            catch (Exception exception)
            {
                UserMessage.InfoMessageAsync(string.Format("Подключение не установлено. {0}", exception.Message),
                    "Тест подключения");
            }
        }
    }
}
